//
//  ComprehensiveSyntaxTest.m
//  test_simple_project
//
//  综合语法特性测试实现文件
//  包含Phase 2和Phase 3的各种Objective-C语法特性实现
//

#import "ComprehensiveSyntaxTest.h"

// 常量定义
NSString * const TestNotificationName = @"TestNotification";
NSString * const TestErrorDomain = @"TestErrorDomain";
NSInteger const TestDefaultTimeout = 30;

@implementation ComprehensiveSyntaxTest {
    // 实例变量 - 包含ARC限定符
    __strong NSString *_strongIvar;
    __weak id _weakIvar;
    __unsafe_unretained id _unsafeIvar;
    
    // 私有实例变量
    NSMutableSet *_privateSet;
    dispatch_semaphore_t _semaphore;
}

#pragma mark - 类方法实现 - Phase 1增强

+ (instancetype)sharedInstance {
    static ComprehensiveSyntaxTest *instance = nil;
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        instance = [[self alloc] init];
    });
    return instance;
}

+ (NSString *)applicationVersion {
    return [[NSBundle mainBundle] objectForInfoDictionaryKey:@"CFBundleShortVersionString"];
}

+ (BOOL)isValidEmail:(NSString *)email {
    NSString *emailRegex = @"[A-Z0-9a-z._%+-]+@[A-Za-z0-9.-]+\\.[A-Za-z]{2,}";
    NSPredicate *emailTest = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", emailRegex];
    return [emailTest evaluateWithObject:email];
}

+ (void)performClassOperation API_AVAILABLE(ios(11.0)) {
    NSLog(@"Performing class operation with modern API");
}

#pragma mark - 初始化方法

- (instancetype)init {
    return [self initWithConfiguration:nil];
}

- (instancetype)initWithConfiguration:(NSDictionary *)configuration {
    self = [super init];
    if (self) {
        // 初始化ARC管理的实例变量
        _strongIvar = @"Strong instance variable";
        _privateSet = [[NSMutableSet alloc] init];
        _semaphore = dispatch_semaphore_create(1);
        
        // 初始化属性
        _privateDataArray = [[NSMutableArray alloc] init];
        _privateQueue = dispatch_queue_create("com.test.private", DISPATCH_QUEUE_SERIAL);
        
        // 处理配置
        if (configuration) {
            _strongProperty = configuration[@"title"];
            _assignProperty = [configuration[@"priority"] integerValue];
        }
        
        [self setupPrivateData];
    }
    return self;
}

- (void)dealloc {
    if (_semaphore) {
        // 注意：在ARC环境下，dispatch_semaphore_t需要手动释放
        _semaphore = nil;
    }
}

#pragma mark - Phase 2特性：异常处理

- (void)demonstrateExceptionHandling {
    @try {
        [self performRiskyOperation];
    }
    @catch (NSException *exception) {
        if ([exception.name isEqualToString:NSRangeException]) {
            NSLog(@"Range exception caught: %@", exception.reason);
        } else if ([exception.name isEqualToString:NSInvalidArgumentException]) {
            NSLog(@"Invalid argument exception: %@", exception.reason);
        } else {
            NSLog(@"General exception caught: %@", exception.name);
        }
        NSLog(@"Exception reason: %@", exception.reason);
    }
    @finally {
        NSLog(@"Exception handling cleanup - this always executes");
    }
}

- (void)performRiskyOperation {
    // 模拟可能抛出异常的操作
    NSArray *testArray = @[@"item1", @"item2", @"item3"];
    
    @try {
        // 故意访问越界索引
        NSString *item = testArray[10];
        NSLog(@"Item: %@", item);
    }
    @catch (NSException *exception) {
        NSLog(@"Inner exception: %@", exception.name);
        // 重新抛出异常
        @throw [NSException exceptionWithName:@"CustomException" 
                                       reason:@"Rethrowing from performRiskyOperation" 
                                     userInfo:@{@"originalException": exception}];
    }
}

#pragma mark - Phase 3特性：同步块

- (void)performSynchronizedOperation {
    // 同步块 - Phase 3特性
    @synchronized(self) {
        NSLog(@"Performing synchronized operation");
        [_privateDataArray addObject:@"synchronized_item"];
        
        // 嵌套同步块
        @synchronized(_privateSet) {
            [_privateSet addObject:@"nested_synchronized_item"];
        }
    }
    
    // 使用其他对象作为同步锁
    @synchronized([ComprehensiveSyntaxTest class]) {
        NSLog(@"Class-level synchronized operation");
    }
}

#pragma mark - 协议实现 - TestDataSourceProtocol

- (NSInteger)numberOfItems {
    return _privateDataArray.count;
}

- (id)itemAtIndex:(NSInteger)index {
    if (index >= 0 && index < _privateDataArray.count) {
        return _privateDataArray[index];
    }
    return nil;
}

- (NSString *)titleForItemAtIndex:(NSInteger)index {
    id item = [self itemAtIndex:index];
    return [NSString stringWithFormat:@"Title for %@", item];
}

#pragma mark - 协议实现 - TestDelegateProtocol

- (void)didSelectItem:(id)item atIndex:(NSInteger)index {
    NSLog(@"Selected item: %@ at index: %ld", item, (long)index);
}

- (BOOL)shouldSelectItem:(id)item atIndex:(NSInteger)index {
    // 简单的选择逻辑
    return item != nil && index >= 0;
}

#pragma mark - Phase 3特性：可用性注解方法

- (void)modernMethod API_AVAILABLE(ios(10.0)) {
    NSLog(@"Modern method implementation - available from iOS 10.0");
    
    // 使用现代API
    if (@available(iOS 10.0, *)) {
        NSLog(@"Using iOS 10.0+ features");
    }
}

- (void)deprecatedMethod API_DEPRECATED("Use modernMethod instead", ios(8.0, 12.0)) {
    NSLog(@"Deprecated method implementation");
    // 调用新方法
    [self modernMethod];
}

- (void)conditionalMethod API_AVAILABLE(ios(9.0)) API_UNAVAILABLE(watchos) {
    NSLog(@"Conditional method - available on iOS 9.0+ but not on watchOS");
}

#pragma mark - 私有方法实现 - 类扩展

- (void)privateMethod {
    NSLog(@"Private method called");
    [self handlePrivateNotification:nil];
}

- (void)setupPrivateData {
    // 设置私有数据
    [_privateDataArray addObjectsFromArray:@[@"item1", @"item2", @"item3"]];
    
    // 注册通知
    [[NSNotificationCenter defaultCenter] addObserver:self
                                             selector:@selector(handlePrivateNotification:)
                                                 name:TestNotificationName
                                               object:nil];
}

- (void)handlePrivateNotification:(NSNotification *)notification {
    NSLog(@"Handling private notification: %@", notification.name);
}

@end

#pragma mark - 分类实现 - Utilities

@implementation ComprehensiveSyntaxTest (Utilities)

- (NSString *)formattedDescription {
    return [NSString stringWithFormat:@"ComprehensiveSyntaxTest: %ld items, strong: %@", 
            (long)[self numberOfItems], self.strongProperty];
}

- (void)logCurrentState {
    NSLog(@"Current state: %@", [self formattedDescription]);
    NSLog(@"Private data count: %ld", (long)self.privateDataArray.count);
}

- (NSDictionary *)toDictionary {
    return @{
        @"strongProperty": self.strongProperty ?: @"",
        @"assignProperty": @(self.assignProperty),
        @"itemCount": @([self numberOfItems]),
        @"readonlyProperty": self.readonlyProperty ?: @""
    };
}

@end

#pragma mark - 分类实现 - NetworkOperations

@implementation ComprehensiveSyntaxTest (NetworkOperations)

- (void)fetchDataWithCompletion:(void(^)(NSData *data, NSError *error))completion {
    // 模拟异步网络请求
    dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
        // 模拟网络延迟
        sleep(1);
        
        // 模拟数据
        NSString *jsonString = @"{\"message\":\"Hello from network\"}";
        NSData *data = [jsonString dataUsingEncoding:NSUTF8StringEncoding];
        
        dispatch_async(dispatch_get_main_queue(), ^{
            if (completion) {
                completion(data, nil);
            }
        });
    });
}

- (void)uploadData:(NSData *)data completion:(void(^)(BOOL success, NSError *error))completion {
    // 模拟数据上传
    dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
        // 模拟上传处理
        BOOL success = data.length > 0;
        NSError *error = nil;
        
        if (!success) {
            error = [NSError errorWithDomain:TestErrorDomain 
                                        code:1001 
                                    userInfo:@{NSLocalizedDescriptionKey: @"No data to upload"}];
        }
        
        dispatch_async(dispatch_get_main_queue(), ^{
            if (completion) {
                completion(success, error);
            }
        });
    });
}

@end

#pragma mark - TestDataModel实现

@implementation TestDataModel

+ (instancetype)modelWithDictionary:(NSDictionary *)dictionary {
    TestDataModel *model = [[self alloc] init];
    model.identifier = dictionary[@"id"];
    model.title = dictionary[@"title"];
    model.priority = [dictionary[@"priority"] integerValue];
    
    NSString *dateString = dictionary[@"created"];
    if (dateString) {
        NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
        formatter.dateFormat = @"yyyy-MM-dd HH:mm:ss";
        model.createdDate = [formatter dateFromString:dateString];
    }
    
    return model;
}

- (NSDictionary *)toDictionary {
    NSMutableDictionary *dict = [NSMutableDictionary dictionary];
    
    if (self.identifier) dict[@"id"] = self.identifier;
    if (self.title) dict[@"title"] = self.title;
    dict[@"priority"] = @(self.priority);
    
    if (self.createdDate) {
        NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
        formatter.dateFormat = @"yyyy-MM-dd HH:mm:ss";
        dict[@"created"] = [formatter stringFromDate:self.createdDate];
    }
    
    return [dict copy];
}

@end

#pragma mark - TestNetworkManager实现

@implementation TestNetworkManager

+ (instancetype)sharedManager {
    static TestNetworkManager *manager = nil;
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        manager = [[self alloc] init];
    });
    return manager;
}

- (instancetype)init {
    self = [super init];
    if (self) {
        NSURLSessionConfiguration *config = [NSURLSessionConfiguration defaultSessionConfiguration];
        config.timeoutIntervalForRequest = TestDefaultTimeout;
        _session = [NSURLSession sessionWithConfiguration:config delegate:self delegateQueue:nil];
    }
    return self;
}

- (void)performNetworkRequest:(NSURLRequest *)request 
                   completion:(void(^)(NSData *data, NSURLResponse *response, NSError *error))completion {
    NSURLSessionDataTask *task = [self.session dataTaskWithRequest:request completionHandler:completion];
    [task resume];
}

#pragma mark - NSURLSessionDelegate

- (void)URLSession:(NSURLSession *)session didBecomeInvalidWithError:(NSError *)error {
    NSLog(@"Session became invalid: %@", error.localizedDescription);
}

#pragma mark - NSURLSessionDataDelegate

- (void)URLSession:(NSURLSession *)session dataTask:(NSURLSessionDataTask *)dataTask 
    didReceiveData:(NSData *)data {
    NSLog(@"Received data: %ld bytes", (long)data.length);
}

@end

#pragma mark - 全局函数实现

void TestGlobalFunction(void) {
    NSLog(@"Test global function called");
}

NSString *TestFormatString(NSString *format, ...) {
    va_list args;
    va_start(args, format);
    NSString *result = [[NSString alloc] initWithFormat:format arguments:args];
    va_end(args);
    return result;
}

void TestModernGlobalFunction(void) API_AVAILABLE(ios(11.0)) {
    NSLog(@"Modern global function - available from iOS 11.0");
}

void TestDeprecatedGlobalFunction(void) API_DEPRECATED("Use TestModernGlobalFunction instead", ios(8.0, 12.0)) {
    NSLog(@"Deprecated global function");
    TestModernGlobalFunction();
}
